<script setup lang="ts">
import { ref, onMounted } from "vue";
import { message } from "ant-design-vue";
import {
  listBuildingByPage,
  addBuilding,
  updateBuilding,
  deleteBuilding,
} from "@/api/building";
import type {
  Building,
  BuildingQueryRequest,
  BuildingAddRequest,
  BuildingUpdateRequest,
} from "@/models/building";
import dayjs from "dayjs";

// 楼栋管理相关状态
const buildings = ref<Building[]>([]);
const buildingTotal = ref(0);
const buildingCurrentPage = ref(1);
const buildingPageSize = ref(6);
const buildingSearchText = ref("");
const buildingIdSearch = ref("");
const buildingLoading = ref(false);

// 楼栋编辑弹窗
const buildingModalVisible = ref(false);
const buildingModalTitle = ref("添加楼栋");
const editingBuilding = ref<BuildingUpdateRequest>({
  buildingId: 0,
  buildingName: "",
  address: "",
});

// 获取楼栋列表
const fetchBuildings = async () => {
  buildingLoading.value = true;
  try {
    const queryRequest: BuildingQueryRequest = {
      current: buildingCurrentPage.value,
      pageSize: buildingPageSize.value,
      buildingName: buildingSearchText.value,
      buildingId: buildingIdSearch.value
        ? parseInt(buildingIdSearch.value)
        : undefined,
    };
    const res = await listBuildingByPage(queryRequest);
    if (res.data.code === 0) {
      buildings.value = res.data.data.records;
      buildingTotal.value = res.data.data.total;
    } else {
      message.error("获取楼栋列表失败");
    }
  } catch (error) {
    message.error("获取楼栋列表失败");
  } finally {
    buildingLoading.value = false;
  }
};

// 重置搜索
const handleReset = () => {
  buildingSearchText.value = "";
  buildingIdSearch.value = "";
  buildingCurrentPage.value = 1;
  fetchBuildings();
};

// 搜索楼栋
const onBuildingSearch = () => {
  buildingCurrentPage.value = 1;
  fetchBuildings();
};

// 处理分页变化
const handleBuildingTableChange = (pagination: any) => {
  buildingCurrentPage.value = pagination.current;
  buildingPageSize.value = pagination.pageSize;
  fetchBuildings();
};

// 添加楼栋
const handleAddBuilding = () => {
  buildingModalTitle.value = "添加楼栋";
  editingBuilding.value = {
    buildingId: 0,
    buildingName: "",
    address: "",
  };
  buildingModalVisible.value = true;
};

// 编辑楼栋
const handleEditBuilding = (record: Building) => {
  buildingModalTitle.value = "编辑楼栋";
  editingBuilding.value = {
    buildingId: record.buildingId,
    buildingName: record.buildingName,
    address: record.address,
  };
  buildingModalVisible.value = true;
};

// 保存楼栋
const handleSaveBuilding = async () => {
  try {
    if (!editingBuilding.value.buildingName || !editingBuilding.value.address) {
      message.error("请填写完整信息");
      return;
    }

    if (editingBuilding.value.buildingId === 0) {
      // 添加楼栋
      const res = await addBuilding(editingBuilding.value);
      if (res.data.code === 0) {
        message.success("添加成功");
      } else {
        message.error(res.data.message || "添加失败");
      }
    } else {
      // 更新楼栋
      const res = await updateBuilding(editingBuilding.value);
      if (res.data.code === 0) {
        message.success("更新成功");
      } else {
        message.error(res.data.message || "更新失败");
      }
    }
    buildingModalVisible.value = false;
    fetchBuildings();
  } catch (error) {
    message.error("操作失败");
  }
};

// 删除楼栋
const handleDeleteBuilding = async (record: Building) => {
  try {
    const res = await deleteBuilding(record.buildingId);
    if (res.data.code === 0) {
      message.success("删除成功");
      fetchBuildings();
    } else {
      message.error(res.data.message || "删除失败");
    }
  } catch (error) {
    message.error("删除失败");
  }
};

onMounted(() => {
  fetchBuildings();
});
</script>

<template>
  <a-card class="info-card">
    <template #title>
      <div class="card-title">
        <building-outlined />
        <span>楼栋信息管理</span>
      </div>
    </template>
    <template #extra>
      <a-space>
        <a-input-number
          v-model:value="buildingIdSearch"
          placeholder="楼栋ID"
          style="width: 120px"
        />
        <a-input-search
          v-model:value="buildingSearchText"
          placeholder="搜索楼栋名称"
          style="width: 200px"
          @search="onBuildingSearch"
        />
        <a-button type="primary" @click="handleAddBuilding">
          添加楼栋
        </a-button>
      </a-space>
    </template>

    <a-table
      :dataSource="buildings"
      :loading="buildingLoading"
      :pagination="{
        total: buildingTotal,
        current: buildingCurrentPage,
        pageSize: buildingPageSize,
        showSizeChanger: true,
        showQuickJumper: true,
      }"
      @change="handleBuildingTableChange"
    >
      <a-table-column key="buildingId" title="楼栋ID" data-index="buildingId" />
      <a-table-column
        key="buildingName"
        title="楼栋名称"
        data-index="buildingName"
      />
      <a-table-column key="address" title="地址" data-index="address" />
      <a-table-column
        key="createTime"
        title="创建时间"
        data-index="createTime"
        :customRender="({ text }) => dayjs(text).format('YYYY-MM-DD HH:mm:ss')"
      />
      <a-table-column key="action" title="操作">
        <template #default="{ record }">
          <a-space>
            <a @click="handleEditBuilding(record)">编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm
              title="确定要删除这个楼栋吗？"
              @confirm="handleDeleteBuilding(record)"
            >
              <a style="color: #ff4d4f">删除</a>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table-column>
    </a-table>

    <!-- 楼栋编辑弹窗 -->
    <a-modal
      v-model:visible="buildingModalVisible"
      :title="buildingModalTitle"
      @ok="handleSaveBuilding"
    >
      <a-form :model="editingBuilding" layout="vertical">
        <a-form-item label="楼栋名称" required>
          <a-input v-model:value="editingBuilding.buildingName" />
        </a-form-item>
        <a-form-item label="地址" required>
          <a-input v-model:value="editingBuilding.address" />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<style scoped>
.info-card {
  margin-bottom: 24px;
}

.card-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 500;
  color: #1f1f1f;
}

.card-title .anticon {
  margin-right: 12px;
  font-size: 20px;
  color: #1890ff;
}
</style>
